package main

import (
	"google.golang.org/grpc"
	pb "grpc-demo/complex/proto"
	"io"
	"log"
	"net"
)

// StreamClientServer is the server API for StreamClient service.
type StreamClientServerImpl struct {
	pb.UnimplementedStreamClientServer
}

// 服务端不断接受从客户端流发送的消息
func (s *StreamClientServerImpl) RouteList(srv pb.StreamClient_RouteListServer) error {
	for {
		res, err := srv.Recv()
		if err == io.EOF {
			// 调用结束后，服务端再发送一个消息
			return srv.SendAndClose(&pb.SimpleResponse{
				Code:  200,
				Value: "OK",
			})
		}
		if err != nil {
			return err
		}
		log.Println(res)
	}
}

func main() {
	// 监听端口
	listener, err := net.Listen("tcp", ":50051")
	if err != nil {
		log.Fatal(err)
	}
	defer listener.Close()
	log.Println("50051端口开始监听")

	// 新建grpc服务器实例
	grpcServer := grpc.NewServer()

	// 在grpc服务器中注册服务
	pb.RegisterStreamClientServer(grpcServer, &StreamClientServerImpl{})

	// 启动grpc服务器
	err = grpcServer.Serve(listener)
	if err != nil {
		log.Fatal(err)
	}
}
